package com.letv.android.client.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ledim.activity.BaseRvListActivity;
import com.ledim.bean.base.BaseListResponse;
import com.ledim.bean.base.BaseResultInfo;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.FrescoUtil;
import com.ledim.utils.LedimBitmapUtils;
import com.ledim.utils.LedimFunctionUtils;
import com.ledim.utils.LogUtil;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.recyclerview.BaseQuickAdapter;
import com.ledim.widget.recyclerview.BaseViewHolder;
import com.ledim.widget.view.LoadingBar;
import com.letv.android.young.client.R;
import java.io.File;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by ccx on 16/6/24.
 * 我的放映厅选择封面图片
 */
public class ChooseRoomPicActivity extends BaseRvListActivity {

    private String ids;
    private LoadingBar loadingBar;
    private File mPhotographFile;
    private String mPhotographPath;
    private String mImagePath;
    private File mAlbumFile;
    public static final int AVATAR_ALBUM = 1;
    public static final int AVATAR_PHOTOGRAPH = 2;
    public static final int AVATAR_ZOOM = 3;
    private Subscription getPicsSubscription;
    private Subscription postPicSubscription;
    private String roomId;
    private View iv_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ids = getIntent().getStringExtra(ConstantUtil.MY_ROOM_URLS);
        roomId = getIntent().getStringExtra(ConstantUtil.MY_ROOM_ID);
        loadingBar = new LoadingBar(this);
        super.onCreate(savedInstanceState);
        TextView textView = findViewByIdExt(R.id.tv_title);
        iv_back = findViewById(R.id.iv_back);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        textView.setText("从图库选择");
        findViewById(R.id.ll_pic).setOnClickListener(this);
        findViewById(R.id.ll_take_photo).setOnClickListener(this);
    }

    @Override
    protected boolean enablePullRefresh() {
        return false;
    }

    @Override
    protected boolean enableLoadMore() {
        return false;
    }

    @Override
    public BaseQuickAdapter getAdapter() {
        return new RoomPicAdapter();
    }

    @Override
    public void getData() {
        if (TextUtils.isEmpty(ids)) {
            mRvPresenter.setData(null, false);
        } else {
            getPicsSubscription = LedimApiServiceFactory.createService(ApiService.class)
                                                        .getMyRoomPicUrls(ids)
                                                        .observeOn(AndroidSchedulers.mainThread())
                                                        .subscribeOn(Schedulers.io())
                                                        .subscribe(new LedimHttpObserver<BaseListResponse<String>>() {
                                                            @Override
                                                            public void onCompleted() {

                                                                super.onCompleted();
                                                            }

                                                            @Override
                                                            public void onError(Throwable e) {
                                                                super.onError(e);
                                                                LogUtil.e("onError--" +
                                                                        e.getMessage());
                                                                mRvPresenter.onErrResponse();
                                                            }

                                                            @Override
                                                            public void onNext(
                                                                    BaseListResponse<String> urls) {
                                                                if (urls.success) {
                                                                    mRvPresenter.setData(urls.data, false);
                                                                } else {
                                                                    mRvPresenter.onErrResponse();
                                                                }
                                                            }
                                                        });
        }
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_choose_myroompic;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_pic:
                //从相册选择
                Intent picture =
                        new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(picture, AVATAR_ALBUM);
                break;
            case R.id.ll_take_photo:
                if (mPhotographFile == null) {
                    mPhotographFile = new File(LedimFunctionUtils.FILEPATH + "/img/");
                    if (!mPhotographFile.exists()) {
                        mPhotographFile.mkdirs();
                    }
                }
                mPhotographPath = mPhotographFile + LedimFunctionUtils.getImageName();
                File file = new File(mPhotographPath);
                Uri imageuri = Uri.fromFile(file);

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageuri);
                intent.putExtra("return-data", false);
                startActivityForResult(intent, AVATAR_PHOTOGRAPH);
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == AVATAR_PHOTOGRAPH) {
                if (mPhotographPath != null) {
                    File files = new File(mPhotographPath);
                    if (files.exists()) {
                        mImagePath = mPhotographPath;
                        Uri selectedImage = Uri.fromFile(new File(mImagePath));
                        mImagePath = startPhotoZoom(selectedImage);
                    }
                }
            } else if (requestCode == AVATAR_ALBUM) {
                Uri selectedImage = data.getData();
                mImagePath = startPhotoZoom(selectedImage);
            } else if (requestCode == AVATAR_ZOOM) {
                if (mImagePath != null && mImagePath.length() > 0) {
                    mImagePath = LedimBitmapUtils.zoomImage(mImagePath, 1024);//图片压缩
                    Intent mIntent = new Intent();
                    mIntent.putExtra(ConstantUtil.ZOOM_FILE_PATH, mImagePath);
                    setResult(ConstantUtil.CHOOSE_FILE_PATHRESPONSE, mIntent);
                    finish();
                }
            }
        }
    }

    private String startPhotoZoom(Uri uri) {
        String fileName;
        if (mAlbumFile == null) {
            mAlbumFile = new File(LedimFunctionUtils.FILEPATH + "/img/");
            if (!mAlbumFile.exists()) {
                mAlbumFile.mkdirs();
            }
        }
        fileName = "/temp.jpg";
        String filePath = mAlbumFile + fileName;
        File loadingFile = new File(filePath);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 320);//裁剪框比例
        intent.putExtra("aspectY", 180);
        intent.putExtra("output", Uri.fromFile(loadingFile));// 输出到文件
        intent.putExtra("outputFormat", "PNG");// 返回格式
        intent.putExtra("noFaceDetection", true); // 去除面部检测
        intent.putExtra("return-data", false); // 不要通过Intent传递截获的图片
        startActivityForResult(intent, AVATAR_ZOOM);
        return filePath;
    }

    class RoomPicAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

        public RoomPicAdapter() {
            super(R.layout.item_choose_roompic, null);
        }

        @Override
        protected void convert(BaseViewHolder helper, final String item, int position) {
            SimpleDraweeView draweeView = helper.getView(R.id.iv_room_photo);
            if (!TextUtils.isEmpty(item)) {
                FrescoUtil.loadUrl(item, draweeView);
            }
            draweeView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    loadingBar.show();
                    postPicSubscription = LedimApiServiceFactory.createService(ApiService.class)
                                                                .setMyRoomPic(roomId, item)
                                                                .observeOn(AndroidSchedulers.mainThread())
                                                                .subscribeOn(Schedulers.io())
                                                                .subscribe(new LedimHttpObserver() {
                                                                    @Override
                                                                    public void onCompleted() {
                                                                        super.onCompleted();
                                                                    }

                                                                    @Override
                                                                    public void onError(
                                                                            Throwable e) {
                                                                        loadingBar.dismiss();
                                                                        super.onError(e);
                                                                        LogUtil.e("onError--" +
                                                                                e.getMessage());
                                                                    }

                                                                    @Override
                                                                    public void onNext(
                                                                            BaseResultInfo o) {
                                                                        loadingBar.dismiss();
                                                                        if (o.success) {
                                                                            ToastUtil.toast("放映厅修改封面成功!");
                                                                            Intent mIntent =
                                                                                    new Intent();
                                                                            mIntent.putExtra(ConstantUtil.CHOOSE_URL_PATH, item);
                                                                            setResult(ConstantUtil.CHOOSE_PICURL_RESPONSE, mIntent);
                                                                            finish();
                                                                        } else {

                                                                        }

                                                                    }
                                                                });
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (getPicsSubscription != null) {
            getPicsSubscription.unsubscribe();
        }
        if (postPicSubscription != null) {
            postPicSubscription.unsubscribe();
        }
        if (loadingBar != null) {
            loadingBar.dismiss();
        }
    }
}
